<?php

//快捷打印输出数据
if (!function_exists('_P')) 
{
    function _P($val, $stop=0, $mod=0){
        header("Content-Type:text/html; charset=utf-8");
        $mod = $mod ? 'var_dump' : 'print_r'; 
        echo '<pre>';
        $mod($val);
        echo '</pre>';
        if($stop)halt("以上是打印输出结果");
    }
}

if (!function_exists('cleanDomain')) 
{
    function cleanDomain($q,$w=0){ 
         //整理域名 $w=1过滤www.前缀 $w=0不过滤
         $q = htmlspecialchars(strtolower(trim($q)));
         if(substr($q,0,7) == "http://" || substr($q,0,8) == "https://" || substr($q,0,6) == "ftp://"){
              $q = str_replace("http:/","",$q);
              $q = str_replace("https:/","",$q);
              $q = str_replace("ftp:/","",$q);
         }
         if(substr($q,0,4) == "www." && $w==1) {
            $q = str_replace("www.","",$q);
         }
         $q = trim($q,"/");
         return $q;
    }
}

if (!function_exists('getCity')) 
{
    //获取所在城市 
    function getCity() 
    { 
        // 获取当前位置所在城市 
        $getIp = clientIP();
        $content = file_get_contents("http://api.map.baidu.com/location/ip?ak=wcPR9wtbvWO5dylkTbpxNXz5l7FydCdd&ip={$getIp}&coor=bd09ll");
        $json = json_decode($content, true); 
        if($json['status'] == 1){
            $address = "";
        }else{
            $address = $json['content']['address']; 
        } 
        return $address; 
    }
}


if (!function_exists('BaiduPush')) 
{
    // 百度推送
    // $urls 推送地址；为一个数组。
    function BaiduPush($urls) 
    { 
        $urls = array($urls);
        $baidutoken = tpCache('sitemap.sitemap_zzbaidutoken');
        $api = 'http://data.zz.baidu.com/urls?site=www.pcfcms88.com&token='.$baidutoken;
        $ch = curl_init();
        $options =  array(
            CURLOPT_URL => $api,
            CURLOPT_POST => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS => implode("\n", $urls),
            CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
        );
        curl_setopt_array($ch, $options);
        $result = curl_exec($ch);
        return $result;
    }
}


if (!function_exists('get_head_pic')) 
{
    //获取头像
    function get_head_pic($pic_url = '')
    {
        $default_pic = \think\facade\request::domain() . '/admin/assets/images/head.png';
        return empty($pic_url) ? $default_pic : $pic_url;
    }
}

if (!function_exists('pcfcmssend_email')) 
{
    /**
     * 邮件发送
     * @param $to    接收人
     * @param string $subject   邮件标题
     * @param string $content   邮件内容(html模板渲染后的内容)
     */
    function pcfcmssend_email($to='', $subject='', $content= array(),  $smtp_config = []){
        // 实例化类库，调用发送邮件
        $emailLogic = new \app\common\logic\EmailLogic();
        $res = $emailLogic->send_email($to, $subject, $content,$smtp_config);
        return $res;
    }
}

if (!function_exists('pcfcmssend_sms')) 
{
    /**
     * 短信发送
     * @param $to    接收人
     * @param $code  接收验证码
     */
    function pcfcmssend_sms($to='',$code){
        // 实例化类库，调用发送邮件
        $smsLogic = new \app\common\logic\SmsLogic();
        $res = $smsLogic->send_msg($to,$code);
        return $res;
    }
}

if (!function_exists('filter_line_return')) 
{
    /**
     *  过滤换行回车符
     * @param     string  $str 字符串信息
     * @return    string
     */
    function filter_line_return($str = '', $replace = '')
    {
        return str_replace(PHP_EOL, $replace, $str);
    }
}

if (!function_exists('clientIP')) 
{
    //客户端IP
    function clientIP() {
        $ip = request()->ip();
        if(preg_match('/^((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1 -9]?\d))))$/', $ip))          
            return $ip;
        else
            return '';
    }
}

if (!function_exists('checkStrHtml')) 
{
    /**
     * 过滤Html标签
     * @param     string  $string  内容
     * @return    string
     */
    function checkStrHtml($string){
        $string = pcftrim_space($string);
        if(is_numeric($string)) return $string;
        if(!isset($string) or empty($string)) return '';
        $string = preg_replace('/[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F]/','',$string);
        $string  = ($string);
        $string = strip_tags($string,""); //清除HTML如<br />等代码
        $string = str_replace("\n", "", $string);//去掉空格和换行
        $string = str_replace("\t","",$string); //去掉制表符号
        $string = str_replace(PHP_EOL,"",$string); //去掉回车换行符号
        $string = str_replace("\r","",$string); //去掉回车
        $string = str_replace("'","‘",$string); //替换单引号
        $string = str_replace("&amp;","&",$string);
        $string = str_replace("=★","",$string);
        $string = str_replace("★=","",$string);
        $string = str_replace("★","",$string);
        $string = str_replace("☆","",$string);
        $string = str_replace("√","",$string);
        $string = str_replace("±","",$string);
        $string = str_replace("‖","",$string);
        $string = str_replace("×","",$string);
        $string = str_replace("∏","",$string);
        $string = str_replace("∷","",$string);
        $string = str_replace("⊥","",$string);
        $string = str_replace("∠","",$string);
        $string = str_replace("⊙","",$string);
        $string = str_replace("≈","",$string);
        $string = str_replace("≤","",$string);
        $string = str_replace("≥","",$string);
        $string = str_replace("∞","",$string);
        $string = str_replace("∵","",$string);
        $string = str_replace("♂","",$string);
        $string = str_replace("♀","",$string);
        $string = str_replace("°","",$string);
        $string = str_replace("¤","",$string);
        $string = str_replace("◎","",$string);
        $string = str_replace("◇","",$string);
        $string = str_replace("◆","",$string);
        $string = str_replace("→","",$string);
        $string = str_replace("←","",$string);
        $string = str_replace("↑","",$string);
        $string = str_replace("↓","",$string);
        $string = str_replace("▲","",$string);
        $string = str_replace("▼","",$string);
        // --过滤微信表情
        $string = preg_replace_callback('/[\xf0-\xf7].{3}/', function($r) { return '';}, $string);
        return $string;
    }
}

if (!function_exists('pcftrim_space')) 
{
    /**
     * 过滤前后空格等多种字符
     *
     * @param string $str 字符串
     * @param array $arr 特殊字符的数组集合
     * @return string
     */
    function pcftrim_space($str, $arr = array())
    {
        if (empty($arr)) {
            $arr = array(' ', '　');
        }
        foreach ($arr as $key => $val) {
            $str = preg_replace('/(^'.$val.')|('.$val.'$)/', '', $str);
        }

        return $str;
    }
}

//判断是手机登录还是电脑登录
if (!function_exists('common_ismobile')) 
{
    function common_ismobile() {
        // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
        if (isset ($_SERVER['HTTP_X_WAP_PROFILE']))
            return "wap";
        //此条摘自TPM智能切换模板引擎，适合TPM开发
        if(isset ($_SERVER['HTTP_CLIENT']) &&'PhoneClient'==$_SERVER['HTTP_CLIENT'])
            return "wap";
        //如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
        if (isset ($_SERVER['HTTP_VIA']))
            //找不到为flase,否则为true
            return stristr($_SERVER['HTTP_VIA'], 'wap') ? true : false;
        //判断手机发送的客户端标志,兼容性有待提高
        if (isset ($_SERVER['HTTP_USER_AGENT'])) {
            $clientkeywords = array(
                'nokia','sony','ericsson','mot','samsung','htc','sgh','lg','sharp','sie-','philips','panasonic','alcatel','lenovo','iphone','ipod','blackberry','meizu','android','netfront','symbian','ucweb','windowsce','palm','operamini','operamobi','openwave','nexusone','cldc','midp','wap','mobile'
            );
            //从HTTP_USER_AGENT中查找手机浏览器的关键字
            if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
                return "wap";
            }
        }
        //协议法，因为有可能不准确，放到最后判断
        if (isset ($_SERVER['HTTP_ACCEPT'])) {
            // 如果只支持wml并且不支持html那一定是移动设备
            // 如果支持wml和html但是wml在html之前则是移动设备
            if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
                return "wap";
            }
        }
        return "pc";
    }
}

//读取文件内容
if (!function_exists('pcftxt')) 
{
    function pcftxt($pcfurl , $type = 1)
    {
        if(file_exists($pcfurl)) {
            $fp = fopen($pcfurl, 'r');
            $content = fread($fp, filesize($pcfurl));
            fclose($fp);
			if($type){
				$ver = $content ? $content : "";
				$str_encoding = mb_convert_encoding($ver, 'UTF-8', 'UTF-8,GBK,GB2312,BIG5');
				$ver1 = explode("\r\n", $str_encoding);				
			}else{
				$ver1 = $content ? $content : "";
			}
        } else {
            $ver1 = "";
        }
        return $ver1;
    }
}

//获取当前CMS版本号
if (!function_exists('getCmsVersion')) 
{
    function getCmsVersion()
    {
        $web_version = tpCache('system.system_version');
        $version_txt_path = ROOT_PATH.'extend/conf/version.txt';
        $version_txt_path = str_replace("\/", "/", $version_txt_path);
        $version_txt_path = str_replace('/','\\' , $version_txt_path);
        if(file_exists($version_txt_path)) {
            $fp = fopen($version_txt_path, 'r');
            $content = fread($fp, filesize($version_txt_path));
            fclose($fp);
            $ver1 = $content ? $content : $web_version;
        } else {
            $ver1 = !empty($web_version) ? $web_version : 'v1.8.0';
        }
        return $ver1;
    }
}

// 用于前端会员订单显示版本号
if (!function_exists('getCmsVersion1')) 
{
    function getCmsVersion1()
    {
		$web_version = tpCache('system.system_version');
        $version_txt_path = ROOT_PATH.'extend/conf/version.txt';
        $version_txt_path = str_replace("\/", "/", $version_txt_path);
        $version_txt_path = str_replace('/','\\' , $version_txt_path);
        if(file_exists($version_txt_path)) {
            $fp = fopen($version_txt_path, 'r');
            $content = fread($fp, filesize($version_txt_path));
            fclose($fp);
            $ver1['version'] = $content ? $content : $web_version;
            $ver1['lastUpdateTime'] = date("Y-m-d H:i:s", filemtime($version_txt_path));
        } else {
            $ver1 = !empty($web_version) ? $web_version : 'v1.8.0';
        }
        return $ver1;
    }
}

if (!function_exists('getCmsVersion2')) 
{
    function getCmsVersion2()
    {
		$web_version = tpCache('system.system_version');
        $version_txt_path = ROOT_PATH.'public/update/version.txt';
        $version_txt_path = str_replace("\/", "/", $version_txt_path);
        $version_txt_path = str_replace('/','\\' , $version_txt_path);
        if(file_exists($version_txt_path)) {
            $fp = fopen($version_txt_path, 'r');
            $content = fread($fp, filesize($version_txt_path));
            fclose($fp);
            $ver1['version'] = $content ? $content : $web_version;
            $ver1['lastUpdateTime'] = date("Y-m-d H:i:s", filemtime($version_txt_path));
        } else {
            $ver1 = !empty($web_version) ? $web_version : 'v1.8.0';
        }
        return $ver1;
    }
}

if (!function_exists('serverIP')) 
{  
    // 服务器端IP
    function serverIP(){   
        return gethostbyname($_SERVER["SERVER_NAME"]);   
    }  
}

if (!function_exists('tp_mkdir')) 
{
    /**
     * 递归创建目录 
     * @param string $path 目录路径，不带反斜杠
     * @param intval $purview 目录权限码
     * @return boolean
     */  
    function tp_mkdir($path, $purview = 0777)
    {
        if (!is_dir($path)) {
            tp_mkdir(dirname($path), $purview);
            if (!mkdir($path, $purview)) {
                return false;
            }
        }
        return true;
    }
}

if (!function_exists('replace_path')) 
{
    /**
     * 将路径斜杆、反斜杠替换为冒号符，适用于IIS服务器在URL上的双重转义限制
     * @param string $filepath 相对路径
     * @param string $replacement 目标字符
     * @param boolean $is_back false为替换，true为还原
     */
    function replace_path($filepath = '', $replacement = ':', $is_back = false)
    {
        if (false == $is_back) {
            $filepath = str_replace(DIRECTORY_SEPARATOR, $replacement, $filepath);
            $filepath = preg_replace('#\/#', $replacement, $filepath);
        } else {
            $filepath = preg_replace('#'.$replacement.'#', '/', $filepath);
            $filepath = str_replace('//', ':/', $filepath);
        }
        return $filepath;
    }
}

if (!function_exists('newisMobile')) 
{
    // 验证手机号码
    function newisMobile($mobile)
    {
        if (preg_match("/^1[3456789]{1}\d{9}$/", $mobile)) {
            return true;
        } else {
            return false;
        }
    }
}

if (!function_exists('isEmail')) 
{
    // 验证邮箱
    function isEmail($email)
    {
        $pattern = '/^[a-z0-9]+([._-][a-z0-9]+)*@([0-9a-z]+\.[a-z]{2,14}(\.[a-z]{2})?)$/i';
        if (preg_match($pattern, $email)) {
            return true;
        } else {
            return false;
        }
    }
}

if (!function_exists('get_default_pic')) 
{
    /**
     * 图片不存在，显示默认无图封面
     * @param string $pic_url 图片路径
     * @param string|boolean $domain 完整路径的域名
     */
    function get_default_pic($pic_url = '', $domain = false)
    {
        if (!is_http_url($pic_url)) {
            if (true === $domain) {
                $domain = request()->domain();
            } else if (false === $domain) {
                $domain = '';
            }
            $pic_url = preg_replace('#^(/[/\w]+)?(/public/upload/|/uploads/)#i', '$2', $pic_url); // 支持子目录
            $realpath = realpath(trim($pic_url, '/'));
            if ( is_file($realpath) && file_exists($realpath) ) {
                $pic_url = $domain  . $pic_url;
            } else {
                $pic_url = $domain  . '/common/images/not_adv.jpg';
            }
        }
        return $pic_url;
    }
}

//密码生成
if (!function_exists('func_encrypt')) 
{
    /**
     * md5加密 
     * @param string $str 字符串
     * @return array
     */
    function func_encrypt($str){
        $auth_code = "FBWQg3f7Psur9E6Usp8j";
        return md5($auth_code.$str);
    }
}

if (!function_exists('pcftime')) 
{
    /**
     * 时间格式化
     * @param int $time
     * @return false|string
     */
    function pcftime($time = 0)
    {
        return date('Y-m-d H:i:s', $time);
    }
}

if (!function_exists('tpCache')) 
{
    /**
     * 获取缓存或者更新缓存，只适用于config表
     * @param string $config_key 缓存文件名称
     * @param array $data 缓存数据  array('k1'=>'v1','k2'=>'v3')
     * @param array $options 缓存配置
     * @return array or string or bool
     */
    function tpCache($config_key,$data = array()){
        $tableName = 'config';
        $table_db = \think\facade\Db::name($tableName);
        $param = explode('.', $config_key);
        $cache_inc_type = $tableName.$param[0];
        $newData = array();
        if(empty($data)){
            $config = \think\facade\Cache::get($cache_inc_type);//直接获取缓存文件
            if(empty($config)){
                //缓存文件不存在就读取数据库
                if ($param[0] == 'global') {
                    $param[0] = 'global';
                    $res = $table_db->where('is_del', 0)->select()->toArray();
                } else {
                    $res = $table_db->where(['inc_type'=> $param[0],'is_del'=> 0])->select()->toArray();
                }
                $config  = array();
                if($res){
                    foreach($res as $k=>$val){
                        if(isset($val) && is_array($val)){
                           $config[$val['name']] = $val['value']; 
                        }
                    }
                    \think\facade\Cache::set($cache_inc_type,$config,PCFCMS_CACHE_TIME);
                }
            }
            if(!empty($param) && count($param)>1){
                $newKey = strtolower($param[1]);
                return isset($config[$newKey]) ? $config[$newKey] : '';
            }else{
                return $config;
            }
        }else{
            //更新缓存
            $result =  $table_db->where(['inc_type'=> $param[0],'is_del'=> 0])->select()->toArray();
            if($result){
                foreach($result as $val){
                    $temp[$val['name']] = $val['value'];
                }
                $add_data = array();
                foreach ($data as $k=>$v){
                    $newK = strtolower($k);
                    $newArr = array(
                        'name'=>$newK,
                        'value'=>$v,
                        'inc_type'=>$param[0],
                        'update_time'   => time(),
                    );
                    if(!isset($temp[$newK])){
                        array_push($add_data, $newArr); //新key数据插入数据库
                    }else{
                        if ($v != $temp[$newK]) {
                            \think\facade\Db::name('config')->where('name',$newK)->update($newArr);//缓存key存在且值有变更新此项
                        }
                    }
                }
                if (!empty($add_data)) {
                    $table_db->insertAll($add_data);
                }
                //更新后的数据库记录
                $newRes = $table_db->where(['inc_type'=> $param[0],'is_del'=> 0])->select()->toArray();
                foreach ($newRes as $rs){
                    $newData[$rs['name']] = $rs['value'];
                }
            }else{
                if ($param[0] != 'global') {
                    foreach($data as $k=>$v){
                        $newK = strtolower($k);
                        $newArr[] = array(
                            'name'=>$newK,
                            'value'=>trim($v),
                            'inc_type'=>$param[0],
                            'update_time' => time(),
                        );
                    }
                    if(!empty($newArr)){
                        $table_db->insertAll($newArr);
                    }
                }
                $newData = $data;
            }
            $result = false;
            $res = $table_db->where('is_del', 0)->select()->toArray();
            if($res){
                $global = array();
                foreach($res as $k=>$val){
                    $global[$val['name']] = $val['value'];
                }
                $result = \think\facade\cache::set($tableName.'global',$global);
            }
            if ($param[0] != 'global') {
                $result = \think\facade\cache::set($cache_inc_type,$newData);
            }
            return $result;
        }
    }
}

if (!function_exists('getUsersConfigData'))
{
    // 专用于获取users_config，会员配置表数据处理。
    function getUsersConfigData($config_key,$data = array()){
        $tableName = 'users_config';
        $table_db = \think\facade\Db::name($tableName);
        $param = explode('.', $config_key);
        $cache_inc_type = $tableName.$param[0];
        if(empty($data)){
            $config = \think\facade\Cache::get($cache_inc_type);//直接获取缓存文件
            if(empty($config)){
                //缓存文件不存在就读取数据库
                if ($param[0] == 'all') {
                    $param[0] = 'all';
                    $res = $table_db->select()->toArray();
                } else {
                    $res = $table_db->where(['inc_type' => $param[0]])->select();
                }
                if($res){
                    foreach($res as $k=>$val){
                        $config[$val['name']] = $val['value'];
                    }
                    \think\facade\Cache::set($cache_inc_type,$config);
                }
            }
            if(!empty($param) && count($param)>1){
                $newKey = strtolower($param[1]);
                return isset($config[$newKey]) ? $config[$newKey] : '';
            }else{
                return $config;
            }
        }else{
            // 更新缓存
            $result =  $table_db->where(['inc_type' => $param[0]])->select()->toArray();
            if($result){
                foreach($result as $val){
                    $temp[$val['name']] = $val['value'];
                }
                $add_data = array();
                foreach ($data as $k=>$v){
                    $newK = strtolower($k);
                    $newArr = array(
                        'name'=>$newK,
                        'value'=>trim($v),
                        'inc_type'=>$param[0],
                        'update_time' => time()
                    );
                    if(!isset($temp[$newK])){
                        array_push($add_data, $newArr); // 新key数据插入数据库
                    }else{
                        if ($v != $temp[$newK]) {
                            $table_db->where(['name' => $newK])->save($newArr);// 缓存key存在且值有变更新此项
                        }
                    }
                }
                if (!empty($add_data)) {
                    $table_db->insertAll($add_data);
                }
                // 更新后的数据库记录
                $newRes = $table_db->where(['inc_type' => $param[0],])->select()->toArray();
                foreach ($newRes as $rs){
                    $newData[$rs['name']] = $rs['value'];
                }
            }else{
                if ($param[0] != 'all') {
                    foreach($data as $k=>$v){
                        $newK = strtolower($k);
                        $newArr[] = array(
                            'name'=>$newK,
                            'value'=>trim($v),
                            'inc_type'=>$param[0],
                            'update_time' => time(),
                        );
                    }
                    $table_db->insertAll($newArr);
                }
                $newData = $data;
            }
            $result = false;
            $res = $table_db->select()->toArray();
            if($res){
                $global = array();
                foreach($res as $k=>$val){
                    $global[$val['name']] = $val['value'];
                }
                $result = \think\facade\Cache::set($tableName.'all',$global);
            }
            if ($param[0] != 'all') {
                $result = \think\facade\Cache::set($cache_inc_type,$newData);
            }
            return $result;
        }
    }
}

if (!function_exists('getupdateData'))
{
    // 专用于获取update_config，更新配置表数据处理。
    function getupdateData($config_key,$data = array()){
        $tableName = 'update_config';
        $table_db = \think\facade\Db::name($tableName);
        $param = explode('.', $config_key);
        $cache_inc_type = $tableName.$param[0];
        if(empty($data)){
            $config = \think\facade\Cache::get($cache_inc_type);//直接获取缓存文件
            if(empty($config)){
                //缓存文件不存在就读取数据库
                if ($param[0] == 'all') {
                    $param[0] = 'all';
                    $res = $table_db->select()->toArray();
                } else {
                    $res = $table_db->where(['inc_type' => $param[0]])->select();
                }
                if($res){
                    foreach($res as $k=>$val){
                        $config[$val['name']] = $val['value'];
                    }
                    \think\facade\Cache::set($cache_inc_type,$config);
                }
            }
            if(!empty($param) && count($param)>1){
                $newKey = strtolower($param[1]);
                return isset($config[$newKey]) ? $config[$newKey] : '';
            }else{
                return $config;
            }
        }else{
            // 更新缓存
            $result =  $table_db->where(['inc_type' => $param[0]])->select()->toArray();
            if($result){
                foreach($result as $val){
                    $temp[$val['name']] = $val['value'];
                }
                $add_data = array();
                foreach ($data as $k=>$v){
                    $newK = strtolower($k);
                    $newArr = array(
                        'name'=>$newK,
                        'value'=>trim($v),
                        'inc_type'=>$param[0],
                        'update_time' => time()
                    );
                    if(!isset($temp[$newK])){
                        array_push($add_data, $newArr); // 新key数据插入数据库
                    }else{
                        if ($v != $temp[$newK]) {
                            $table_db->where(['name' => $newK])->save($newArr);// 缓存key存在且值有变更新此项
                        }
                    }
                }
                if (!empty($add_data)) {
                    $table_db->insertAll($add_data);
                }
                // 更新后的数据库记录
                $newRes = $table_db->where(['inc_type' => $param[0],])->select()->toArray();
                foreach ($newRes as $rs){
                    $newData[$rs['name']] = $rs['value'];
                }
            }else{
                if ($param[0] != 'all') {
                    foreach($data as $k=>$v){
                        $newK = strtolower($k);
                        $newArr[] = array(
                            'name'=>$newK,
                            'value'=>trim($v),
                            'inc_type'=>$param[0],
                            'update_time' => time(),
                        );
                    }
                    $table_db->insertAll($newArr);
                }
                $newData = $data;
            }
            $result = false;
            $res = $table_db->select()->toArray();
            if($res){
                $global = array();
                foreach($res as $k=>$val){
                    $global[$val['name']] = $val['value'];
                }
                $result = \think\facade\Cache::set($tableName.'all',$global);
            }
            if ($param[0] != 'all') {
                $result = \think\facade\Cache::set($cache_inc_type,$newData);
            }
            return $result;
        }
    }
}

if (!function_exists('write_global_params')) 
{
    /**
     * 写入全局内置参数
     * @return array
     */
    function write_global_params($options = null)
    {
        $gzpcfglobal = get_global();
        $webConfigParams = \think\facade\Db::name('config')->where(['inc_type'=> 'web','is_del'=> 0])->select()->toArray();
        if (!empty($webConfigParams)) {
            $rtn = array();
            foreach ($webConfigParams as $k => $v) {
                $rtn[$v['name']] = $v;
            }
            $webConfigParams = $rtn;
        }
        $web_basehost = !empty($webConfigParams['web_basehost']) ? $webConfigParams['web_basehost']['value'] : '';//网站根网址
        $web_cmspath = !empty($webConfigParams['web_cmspath']) ? $webConfigParams['web_cmspath']['value'] : '';//安装目录
        //启用绝对网址，开启此项后附件、栏目连接、arclist内容等都使用http路径
        $web_multi_site = !empty($webConfigParams['web_multi_site']) ? $webConfigParams['web_multi_site']['value'] : '';
        if($web_multi_site == 1){
            $web_mainsite = $web_basehost.$web_cmspath;
        }else{
            $web_mainsite = '';
        }
        //CMS安装目录的网址
        $param['web_cmsurl'] = $web_mainsite;
        $param['web_templets_dir'] = '/template/'.$gzpcfglobal['admin_config']['tpl_theme']; // 前台模板根目录
        $param['web_templeturl'] = $web_mainsite.$param['web_templets_dir']; // 前台模板根目录的网址
        $param['web_templets_pc'] = $web_mainsite.$param['web_templets_dir'].'/pc'; // 前台PC模板主题
        $param['web_templets_m'] = $web_mainsite.$param['web_templets_dir'].'/mobile'; // 前台手机模板主题
        $param['web_pcfcms'] = str_replace('#', '', '#h#t#t#p#:#/#/#w#w#w#.#p#c#f#c#m#s#.#c#o#m#'); //网址
        //将内置的全局变量(页面上没有入口更改的全局变量)存储到web版块里
        $inc_type = 'web';
        foreach ($param as $key => $val) {
            if (preg_match("/^".$inc_type."_(.)+/i", $key) !== 1) {
                $nowKey = strtolower($inc_type.'_'.$key);
                $param[$nowKey] = $val;
            }
        }
        tpCache($inc_type, $param, $options);
    }
}

if (!function_exists('delFile')) 
{  
    /**
     * 递归删除文件夹
     *
     * @param string $path 目录路径
     * @param boolean $delDir 是否删除空目录
     * @return boolean
     */
    function delFile($path, $delDir = FALSE) {
        if(!is_dir($path))
            return FALSE;       
        $handle = @opendir($path);
        if ($handle) {
            while (false !== ( $item = readdir($handle) )) {
                if ($item != "." && $item != "..")
                    is_dir("$path/$item") ? delFile("$path/$item", $delDir) : @unlink("$path/$item");
            }
            closedir($handle);
            if ($delDir) {
                return @rmdir($path);
            }
        }else {
            if (file_exists($path)) {
                return @unlink($path);
            } else {
                return FALSE;
            }
        }
    }
}

if (!function_exists('eyIntval')) 
{
    /**
     * 强制把数值转为整型
     * @param mixed        $data 任意数值
     * @return mixed
     */
    function eyIntval($data)
    {
        if (is_array($data)) {
            foreach ($data as $key => $val) {
                $data[$key] = intval($val);
            }
        } else if (is_string($data) && stristr($data, ',')) {
            $arr = explode(',', $data);
            foreach ($arr as $key => $val) {
                $arr[$key] = intval($val);
            }
            $data = implode(',', $arr);
        } else {
            $data = intval($data);
        }
        return $data;
    }
}

if (!function_exists('eyPreventShell')) 
{
    /**
     * 验证是否shell注入
     * @param mixed        $data 任意数值
     * @return mixed
     */
    function eyPreventShell($data = '')
    {
        $data = true;
        if (is_string($data) && (preg_match('/^phar:\/\//i', $data) || stristr($data, 'phar://'))) {
            $data = false;
        } else if (is_numeric($data)) {
            $data = intval($data);
        }
        return $data;
    }
}

if (!function_exists('strip_sql')) 
{
    /**
     * 转换SQL关键字
     * @param unknown_type $string
     * @return unknown
     */
    function strip_sql($string) {
        $pattern_arr = array(
                "/\bunion\b/i",
                "/\bselect\b/i",
                "/\bupdate\b/i",
                "/\bdelete\b/i",
                "/\boutfile\b/i",
                "/\bchar\b/i",
                "/\bconcat\b/i",
                "/\btruncate\b/i",
                "/\bdrop\b/i",            
                "/\binsert\b/i", 
                "/\brevoke\b/i", 
                "/\bgrant\b/i",      
                "/\breplace\b/i", 
                "/\brename\b/i",
                "/\bdeclare\b/i",
                "/\bexec\b/i",         
                "/\bdelimiter\b/i",
                "/\bphar\b\:/i",
                "/\bphar\b/i",
                "/\@(\s*)\beval\b/i",
                "/\beval\b/i",
        );
        $replace_arr = array(
                'ｕｎｉｏｎ',
                'ｓｅｌｅｃｔ',
                'ｕｐｄａｔｅ',
                'ｄｅｌｅｔｅ',
                'ｏｕｔｆｉｌｅ',
                'ｃｈａｒ',
                'ｃｏｎｃａｔ',
                'ｔｒｕｎｃａｔｅ',
                'ｄｒｏｐ',            
                'ｉｎｓｅｒｔ',
                'ｒｅｖｏｋｅ',
                'ｇｒａｎｔ',
                'ｒｅｐｌａｃｅ',
                'ｒｅｎａｍｅ',
                'ｄｅｃｌａｒｅ',                
                'ｅｘｅｃ',         
                'ｄｅｌｉｍｉｔｅｒ',
                'ｐｈａｒ',
                'ｐｈａｒ',
                '＠ｅｖａｌ',
                'ｅｖａｌ',
        );
        return is_array($string) ? array_map('strip_sql', $string) : preg_replace($pattern_arr, $replace_arr, $string);
    }
}

if (!function_exists('respose')) 
{
    /**
     * 参数 is_jsonp 为true，表示跨域ajax请求的返回值
     * @param string $res 数组
     * @param bool $is_jsonp 是否跨域
     * @return string
     */
    function respose($res, $is_jsonp = false){
        if (true === $is_jsonp) {
            halt(input('callback')."(".json_encode($res).")");
        } else {
            halt(json_encode($res));
        }
    }
}

if (!function_exists('handle_subdir_pic')) 
{
    /**
     * 处理子目录与根目录的图片平缓切换
     * @param string $str 图片路径或html代码
     */
    function handle_subdir_pic($str = '', $type = 'img')
    {
        $root_dir = root_path();
        switch ($type) {
            case 'img':
                if (!is_http_url($str) && !empty($str)) {
                    $str = preg_replace('#^(/[/\w]+)?(public/uploads/|public/uploads/)#i', $root_dir.'$2', $str);
                }else if (is_http_url($str) && !empty($str)) {
                    $str     = preg_replace('#^(/[/\w]+)?(public/uploads/|public/uploads/)#i', $root_dir.'$2', $str);
                    $StrData = parse_url($str);
                    $strlen  = strlen($root_dir);
                }
                break;
            case 'html':
                    $str = preg_replace('#(.*)(\#39;|&quot;|"|\')(/[/\w]+)?(public/uploads/|public/plugins/|public/uploads/)(.*)#iU', '$1$2'.$root_dir.'$4$5', $str);
                break;
            case 'soft':
                if (!is_http_url($str) && !empty($str)) {
                    $str = preg_replace('#^(/[/\w]+)?(public/uploads/soft/|public/uploads/soft/)#i', '$2', $str);
                }
                break;
            default:
                break;
        }
        return $str;
    }
}

if (!function_exists('is_http_url')) 
{
    /**
     * 判断url是否完整的链接
     * @param  string $url 网址
     * @return boolean
     */
    function is_http_url($url)
    {
        preg_match("/^((\w)*:)?(\/\/).*$/", $url, $match);
        if (empty($match)) {
            return false;
        } else {
            return true;
        }
    }
}

if (!function_exists('getAdminInfo')) 
{
    /**
     * 获取管理员登录信息
     */
    function getAdminInfo($admin_id = 0)
    {
        $admin_info = [];
        $admin_id = empty($admin_id) ? \think\facade\session::get('admin_id') : $admin_id;
        if (0 < intval($admin_id)) {
            $admin_info = \think\facade\Db::name('admin')
                ->field('a.*, b.name AS role_name')
                ->alias('a')
                ->join('auth_role b', 'b.id = a.role_id', 'LEFT')
                ->where("a.admin_id", $admin_id)
                ->find();
            if (!empty($admin_info)) {
                // 头像
                empty($admin_info['head_pic']) && $admin_info['head_pic'] = get_head_pic($admin_info['head_pic']);
                // 权限组
                $admin_info['role_id'] = !empty($admin_info['role_id']) ? $admin_info['role_id'] : -1;
                if ($admin_info['role_id'] == -1) {
                    if (!empty($admin_info['parent_id'])) {
                        $role_name = '超级管理员';
                    } else {
                        $role_name = '创始人';
                    }
                } else {
                    $role_name = $admin_info['role_name'];
                }
                $admin_info['role_name'] = $role_name;
            }
        }
        return $admin_info;
    }
}

if (!function_exists('schemaTable')) 
{
    /**
     * 重新生成数据表缓存字段文件
     */
    function schemaTable($name)
    {
        $table = $name;
        $prefix = config('database.connections.mysql.prefix');
        if (!preg_match('/^'.$prefix.'/i', $name)) {
            $table = $prefix.$name;
        }
        //调用命令行的指令
        \think\facade\Console::call('optimize:schema', ['--table', $table]);
    }
}

if (!function_exists('get_global')) 
{
    /**
     * 获取全局配置文件
     */
    function get_global($name = 'global')
    {            
        $arr = include base_path().'extra/'.$name.'.php';
        return $arr;
    }
}

if (!function_exists('group_same_key')) 
{ 
    /**
     * 将二维数组以元素的某个值作为键，并归类数组
     * array( array('name'=>'aa','type'=>'pay'), array('name'=>'cc','type'=>'pay') )
     * array('pay'=>array( array('name'=>'aa','type'=>'pay') , array('name'=>'cc','type'=>'pay') ))
     * @param $arr 数组
     * @param $key 分组值的key
     * @param $count 每个子数组最多个数 为0或者为空表示不限制个数
     * @return array
     */
    function group_same_key($arr,$key,$count = 0){
        $new_arr = array();
        foreach($arr as $k=>$v ){
            if (empty($count) || count($new_arr[$v[$key]]) < $count ){
                $new_arr[$v[$key]][] = $v;
            }
        }
        return $new_arr;
    }
}


if (!function_exists('array_unset_tt')) 
{ 
    //去重复数组
    function array_unset_tt($arr,$key='id'){
        //建立一个目标数组
        $res = array();
        foreach ($arr as $value) {
            //查看有没有重复项
            if(isset($res[$value[$key]])){
                unset($value[$key]);  //有：销毁
            }else{
                $res[$value[$key]] = $value;
            }
        }
        return $res;
    }
}


if (!function_exists('testWriteAble')) 
{
    /**
     * 测试目录路径是否有写入权限
     * @param string $d 目录路劲
     * @return boolean
     */
    function testWriteAble($filepath)
    {
        $tfile = 'session_pcfcms.txt';
        $fp = @fopen($filepath.$tfile,'w');
        if(!$fp) {
            return false;
        }else {
            fclose($fp);
            $rs = @unlink($filepath.$tfile);
            return true;
        }
    }
}

if (!function_exists('get_rand_str')) 
{ 
    /**
     * 获取随机字符串
     * @param int $randLength  长度
     * @param int $addtime  是否加入当前时间戳
     * @param int $includenumber   是否包含数字
     * @return string
     */
    function get_rand_str($randLength=6,$addtime=1,$includenumber=0){
        if (1 == $includenumber){
            $chars='abcdefghijklmnopqrstuvwxyzABCDEFGHJKLMNPQEST123456789';
        } else if (2 == $includenumber) {
            $chars='123456789';
        } else {
            $chars='abcdefghijklmnopqrstuvwxyz';
        }
        $len=strlen($chars);
        $randStr='';
        for ($i=0;$i<$randLength;$i++){
            $randStr.=$chars[rand(0,$len-1)];
        }
        $tokenvalue=$randStr;
        if ($addtime){
            $tokenvalue=$randStr.time();
        }
        return $tokenvalue;
    }
}

// 获取拼音以gbk编码为准
if ( ! function_exists('get_pinyin'))
{
    function get_pinyin($str, $ishead=0, $isclose=1)
    {
        $s1 = iconv("UTF-8","gb2312", $str);
        $s2 = iconv("gb2312","UTF-8", $s1);
        if($s2 == $str){$str = $s1;}
        $pinyins = array();
        $restr = '';
        $str = trim($str);
        $slen = strlen($str);
        if($slen < 2)
        {
            return $str;
        }
        if(empty($pinyins))
        {
            $fp = fopen(root_path().'extend/conf/pinyin.dat', 'r');
            while(!feof($fp))
            {
                $line = trim(fgets($fp));
                $pinyins[$line[0].$line[1]] = substr($line, 3, strlen($line)-3);
            }
            fclose($fp);
        }
        for($i=0; $i<$slen; $i++)
        {
            if(ord($str[$i])>0x80)
            {
                $c = $str[$i].$str[$i+1];
                $i++;
                if(isset($pinyins[$c]))
                {
                    if($ishead==0)
                    {
                        $restr .= $pinyins[$c];
                    }
                    else
                    {
                        $restr .= $pinyins[$c][0];
                    }
                }else
                {
                    $restr .= "_";
                }
            }else if( preg_match("/[a-z0-9]/i", $str[$i]) )
            {
                $restr .= $str[$i];
            }
            else
            {
                $restr .= "_";
            }
        }
        if($isclose==0)
        {
            unset($pinyins);
        }
        return strtolower($restr);
    }
}

if (!function_exists('convert_arr_key')) 
{
    /**
     * 将数据库中查出的列表以指定的 id 作为数组的键名 
     * @param array $arr 数组
     * @param string $key_name 数组键名
     * @return array
     */
    function convert_arr_key($arr, $key_name)
    {
        if (function_exists('array_column')) {
            return array_column($arr, null, $key_name);
        }
        $arr2 = array();
        foreach($arr as $key => $val){
            $arr2[$val[$key_name]] = $val;        
        }
        return $arr2;
    }
}

// 追加指定内嵌样式到编辑器内容的img标签，兼容图片自动适应页面
if (!function_exists('img_style_wh')) 
{
    function img_style_wh($content = '', $title = '')
    {
        if (!empty($content)) {
            preg_match_all('/<img.*(\/)?>/iUs', $content, $imginfo);
            $imginfo = !empty($imginfo[0]) ? $imginfo[0] : [];
            if (!empty($imginfo)) {
                $num = 1;
                $appendStyle = "max-width:100%!important;height:auto;";
                $title = preg_replace('/("|\')/i', '', $title);
                foreach ($imginfo as $key => $imgstr) {
                    $imgstrNew = $imgstr;
                    
                    // 兼容已存在的多重追加样式，处理去重
                    if (stristr($imgstrNew, $appendStyle.$appendStyle)) {
                        $imgstrNew = preg_replace('/'.$appendStyle.$appendStyle.'/i', '', $imgstrNew);
                    }
                    if (stristr($imgstrNew, $appendStyle)) {
                        $content = str_ireplace($imgstr, $imgstrNew, $content);
                        $num++;
                        continue;
                    }

                    // 追加style属性
                    $imgstrNew = preg_replace('/style(\s*)=(\s*)[\'|\"](.*?)[\'|\"]/i', 'style="'.$appendStyle.'${3}"', $imgstrNew);
                    if (!preg_match('/<img(.*?)style(\s*)=(\s*)[\'|\"](.*?)[\'|\"](.*?)[\/]?(\s*)>/i', $imgstrNew)) {
                        // 新增style属性
                        $imgstrNew = str_ireplace('<img', "<img style=\"".$appendStyle."\" ", $imgstrNew);
                    }

                    // 追加alt属性
                    $altNew = $title."(图{$num})";
                    $imgstrNew = preg_replace('/alt(\s*)=(\s*)[\'|\"]([\w\.]*?)[\'|\"]/i', 'alt="'.$altNew.'"', $imgstrNew);
                    if (!preg_match('/<img(.*?)alt(\s*)=(\s*)[\'|\"](.*?)[\'|\"](.*?)[\/]?(\s*)>/i', $imgstrNew)) {
                        // 新增alt属性
                        $imgstrNew = str_ireplace('<img', "<img alt=\"{$altNew}\" ", $imgstrNew);
                    }

                    // 追加title属性
                    $titleNew = $title."(图{$num})";
                    $imgstrNew = preg_replace('/title(\s*)=(\s*)[\'|\"]([\w\.]*?)[\'|\"]/i', 'title="'.$titleNew.'"', $imgstrNew);
                    if (!preg_match('/<img(.*?)title(\s*)=(\s*)[\'|\"](.*?)[\'|\"](.*?)[\/]?(\s*)>/i', $imgstrNew)) {
                        // 新增alt属性
                        $imgstrNew = str_ireplace('<img', "<img alt=\"{$titleNew}\" ", $imgstrNew);
                    }
                    // 新的img替换旧的img
                    $content = str_ireplace($imgstr, $imgstrNew, $content);
                    $num++;
                }
            }
        }
        return $content;
    }
}

// 生成一个随机字符 
if (!function_exists('dd2char'))
{
    function dd2char($ddnum)
    {
        $ddnum = strval($ddnum);
        $slen = strlen($ddnum);
        $okdd = '';
        $nn = '';
        for($i=0;$i<$slen;$i++)
        {
            if(isset($ddnum[$i+1]))
            {
                $n = $ddnum[$i].$ddnum[$i+1];
                if( ($n>96 && $n<123) || ($n>64 && $n<91) )
                {
                    $okdd .= chr($n);
                    $i++;
                }
                else
                {
                    $okdd .= $ddnum[$i];
                }
            }
            else
            {
                $okdd .= $ddnum[$i];
            }
        }
        return $okdd;
    }
}

// 获取阅读权限 
if ( ! function_exists('get_arcrank_list'))
{
    function get_arcrank_list()
    {
        $result = \think\facade\Db::name('arcrank')->order('id asc')->column('*', 'rank');
        return $result;
    }
}

// 获取指定栏目的文档数
if (!function_exists('get_total_arc')) 
{
    function get_total_arc($typeid)
    {
        $pcfglobal = get_global();
        $map=[];
        $total = 0;
        $current_channel = \think\facade\Db::name('arctype')->where('id', $typeid)->value('current_channel');
        $allow_release_channel = $pcfglobal['allow_release_channel'];
        if (in_array($current_channel, $allow_release_channel)) { 
            // 能发布文档的模型
            $Arctype = new app\common\model\Arctype;
            $result = $Arctype->getHasChildren($typeid);
            $typeidArr = get_arr_column($result, 'id');
            $map[]= ['typeid','IN',$typeidArr];
            $map[]= ['channel','=',$current_channel];
            $map[]= ['is_del','=',0];
            $total = \think\facade\Db::name('archives')->where($map)->count();
        } 
        return $total;
    }
}

// URL模式下拉列表
if (!function_exists('get_seo_pseudo_list')) 
{
    function get_seo_pseudo_list($key = '')
    {
        $data = array(
            1   => '动态URL',
            //2   => '静态页面',
            3   => '伪静态化',
        );
        return isset($data[$key]) ? $data[$key] : $data;
    }
}

if (!function_exists('get_controller_byct')) 
{
    /**
     * 根据模型ID获取控制器的名称
     * @return mixed
     */
    function get_controller_byct($current_channel)
    {
        $Channeltype = new \app\common\model\ChannelType;
        $channeltype_info = $Channeltype->getInfo($current_channel);
        return $channeltype_info['ctl_name'];
    }
}

if (!function_exists('thumb_img')) 
{
    /**
     * 缩略图 从原始图来处理出来
     * @param type $original_img  图片路径
     * @param type $width     生成缩略图的宽度
     * @param type $height    生成缩略图的高度
     * @param type $thumb_mode    生成方式
     */
    function thumb_img($original_img = '', $width = '', $height = '', $thumb_mode = '')
    {
        // 缩略图配置
        static $thumbConfig = null;
        null === $thumbConfig && $thumbConfig = tpCache('thumb');
        $thumbextra = config('global.thumb');
        if (!empty($width) || !empty($height) || !empty($thumb_mode)) { 
            // 单独在模板里调用，不受缩略图全局开关影响
        } else { 
            // 非单独模板调用，比如内置的arclist\list标签里
            if (empty($thumbConfig['thumb_open'])) {
                return $original_img;
            }
        }

        // 缩略图优先级别高于七牛云，自动把七牛云的图片路径转为本地图片路径，并且进行缩略图
        //$original_img = is_local_images($original_img);

        // 未开启缩略图，或远程图片
        if (is_http_url($original_img) || stristr($original_img, '/common/images/not_adv.jpg')) {
            return $original_img;
        } else if (empty($original_img)) {
            return '/common/images/not_adv.jpg';
        }
        // 图片文件名
        $filename = '';
        $imgArr = explode('/', $original_img);    
        $imgArr = end($imgArr);
        $filename = preg_replace("/\.([^\.]+)$/i", "", $imgArr);
        $file_ext = preg_replace("/^(.*)\.([^\.]+)$/i", "$2", $imgArr);
        // 如果图片参数是缩略图，则直接获取到原图，并进行缩略处理
        if (preg_match('/\/uploads\/thumb\/\d{1,}_\d{1,}\//i', $original_img)) {
            $pattern = root_path().'public/uploads/allimg/*/'.$filename;
            if (in_array(strtolower($file_ext), ['jpg','jpeg'])) {
                $pattern .= '.jp*g';
            } else {
                $pattern .= '.'.$file_ext;
            }
            $original_img_tmp = glob($pattern);
            if (!empty($original_img_tmp)) {
                $original_img = '/'.current($original_img_tmp);
            }
        } else {
            if ('bmp' == $file_ext && version_compare(PHP_VERSION,'7.2.0','<')) {
                return $original_img;
            }
        }
        $original_img1 = preg_replace('#^#i', '', handle_subdir_pic($original_img));
        $original_img1 = '.' . $original_img1; // 相对路径
        //获取图像信息
        $info = @getimagesize($original_img1);
        //检测图像合法性
        if (false === $info || (IMAGETYPE_GIF === $info[2] && empty($info['bits']))) {
            return $original_img;
        } else {
            if (!empty($info['mime']) && stristr($info['mime'], 'bmp') && version_compare(PHP_VERSION,'7.2.0','<')) {
                return $original_img;
            }
        }
        // 缩略图宽高度
        empty($width) && $width = !empty($thumbConfig['thumb_width']) ? $thumbConfig['thumb_width'] : $thumbextra['width'];
        empty($height) && $height = !empty($thumbConfig['thumb_height']) ? $thumbConfig['thumb_height'] : $thumbextra['height'];
        $width = intval($width);
        $height = intval($height);
        //判断缩略图是否存在
        $path = "uploads/thumb/{$width}_{$height}/";
        $img_thumb_name = "{$filename}";
        // 已经生成过这个比例的图片就直接返回了
        if (is_file($path . $img_thumb_name . '.jpg')) return '/' . $path . $img_thumb_name . '.jpg';
        if (is_file($path . $img_thumb_name . '.jpeg')) return '/' . $path . $img_thumb_name . '.jpeg';
        if (is_file($path . $img_thumb_name . '.gif')) return '/' . $path . $img_thumb_name . '.gif';
        if (is_file($path . $img_thumb_name . '.png')) return '/' . $path . $img_thumb_name . '.png';
        if (is_file($path . $img_thumb_name . '.bmp')) return '/' . $path . $img_thumb_name . '.bmp';
        if (!is_file($original_img1)) {
            return '/common/images/not_adv.jpg';
        }
        try {
            $image = \think\Image::open($original_img1);
            $img_thumb_name = $img_thumb_name.'.'.$image->type();
            // 生成缩略图
            !is_dir($path) && mkdir($path, 0777, true);
            // 填充颜色
            $thumb_color = !empty($thumbConfig['thumb_color']) ? $thumbConfig['thumb_color'] : $thumbextra['color'];
            if (!empty($thumb_mode)) {
                $thumb_mode = intval($thumb_mode);
            } else {
                $thumb_mode = !empty($thumbConfig['thumb_mode']) ? $thumbConfig['thumb_mode'] : $thumbextra['mode'];
            }
            1 == $thumb_mode && $thumb_mode = 6; // 按照固定比例拉伸
            2 == $thumb_mode && $thumb_mode = 2; // 填充空白
            if (3 == $thumb_mode) {
                $img_width = $image->width();
                $img_height = $image->height();
                if ($width < $img_width && $height < $img_height) {
                    // 先进行缩略图等比例缩放类型，取出宽高中最小的属性值
                    $min_width = ($img_width < $img_height) ? $img_width : 0;
                    $min_height = ($img_width > $img_height) ? $img_height : 0;
                    if ($min_width > $width || $min_height > $height) {
                        if (0 < intval($min_width)) {
                            $scale = $min_width / min($width, $height);
                        } else if (0 < intval($min_height)) {
                            $scale = $min_height / $height;
                        } else {
                            $scale = $min_width / $width;
                        }
                        $s_width  = $img_width / $scale;
                        $s_height = $img_height / $scale;
                        //按照原图的比例生成一个最大为$width*$height的缩略图并保存
                        $image->thumb($s_width, $s_height, 1, $thumb_color)->save($path.$img_thumb_name, NULL, 100); 
                    }
                }
                $thumb_mode = 3; // 截减
            }
            //按照原图的比例生成一个最大为$width*$height的缩略图并保存
            $image->thumb($width, $height, $thumb_mode, $thumb_color)->save($path . $img_thumb_name, NULL, 100); 

            //图片水印处理
            $water = tpCache('water');
            if($water['is_mark']==1 && $water['is_thumb_mark'] == 1 && $image->width()>$water['mark_width'] && $image->height()>$water['mark_height']){
                $imgresource = './' . $path . $img_thumb_name;
                if($water['mark_type'] == 'text'){
                    $ttf = public_path().'public/common/font/hgzb.ttf';
                    if (file_exists($ttf)) {
                        $size = $water['mark_txt_size'] ? $water['mark_txt_size'] : 30;
                        $color = $water['mark_txt_color'] ? $water['mark_txt_color'] : '#000000';
                        if (!preg_match('/^#[0-9a-fA-F]{6}$/', $color)) {
                            $color = '#000000';
                        }
                        $transparency = intval((100 - $water['mark_degree']) * (127/100));
                        $color.= dechex($transparency);
                        $image->open($imgresource)->text($water['mark_txt'], $ttf, $size, $color, $water['mark_sel'])->save($imgresource);
                        $return_data['mark_txt'] = $water['mark_txt'];
                    }
                }else{
                    $water['mark_img'] = preg_replace('#^(/[/\w]+)?(/public/uploads/|/uploads/)#i', '$2', $water['mark_img']); // 支持子目录
                    $waterPath = public_path()."public".$water['mark_img'];
                    $waterPath = str_replace("\/", "/", $waterPath);
                    if (eyPreventShell($waterPath) && file_exists($waterPath)) {
                        $quality = $water['mark_quality'] ? $water['mark_quality'] : 80;
                        $waterTempPath = dirname($waterPath).'/temp_'.basename($waterPath);
                        $image->open($waterPath)->save($waterTempPath, null, $quality);
                        $image->open($imgresource)->water($waterTempPath, $water['mark_sel'], $water['mark_degree'])->save($imgresource);
                        @unlink($waterTempPath);
                    }
                }
            }
            
            $img_url = './'.$path.$img_thumb_name;
            return $img_url;
        } catch (think\Exception $e) {
            return $original_img;
        }
    }
}

if (!function_exists('is_local_images')) 
{
    /**
     * 判断远程链接是否属于本地图片，并返回本地图片路径
     * @param string $pic_url 图片地址
     * @param boolean $returnbool 返回类型，false 返回图片路径，true 返回布尔值
     */
    function is_local_images($pic_url = '', $returnbool = false)
    {
        $picPath  = parse_url($pic_url, PHP_URL_PATH);
        if (!empty($picPath) && file_exists('.'.$picPath)) {
            $picPath = preg_replace('#^/#i', '/', $picPath);
            $pic_url = $picPath;
            if (true == $returnbool) {
                return $pic_url;
            }
        }
        if (true == $returnbool) {
            return false;
        } else {
            return $pic_url;
        }
    }
}

if (!function_exists('text_msubstr')) 
{
    /**
     * 针对多语言截取，其他语言的截取是中文语言的2倍长度
     * @param string $str 需要转换的字符串
     * @param string $start 开始位置
     * @param string $length 截取长度
     * @param string $suffix 截断显示字符
     * @param string $charset 编码格式
     * @return string
     */
    function text_msubstr($str='', $start=0, $length=NULL, $suffix=false, $charset="utf-8") {
        return pcfmsubstr($str, $start, $length, $suffix, $charset);
    }
}

if (!function_exists('pcfmsubstr')) 
{
    /**
     * 字符串截取，支持中文和其他编码
     * @param string $str 需要转换的字符串
     * @param string $start 开始位置
     * @param string $length 截取长度
     * @param string $suffix 截断显示字符
     * @param string $charset 编码格式
     */
    function pcfmsubstr($str='', $start=0, $length=NULL, $suffix=false, $charset="utf-8") {
        if(function_exists("mb_substr"))
            $slice = mb_substr($str, $start, $length, $charset);
        elseif(function_exists('iconv_substr')) {
            $slice = iconv_substr($str,$start,$length,$charset);
            if(false === $slice) {
                $slice = '';
            }
        }else{
            $re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
            $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
            $re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
            $re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
            preg_match_all($re[$charset], $str, $match);
            $slice = join("",array_slice($match[0], $start, $length));
        }
        $str_len = strlen($str); // 原字符串长度
        $slice_len = strlen($slice); // 截取字符串的长度
        if ($slice_len < $str_len) {
            $slice = $suffix ? $slice.'...' : $slice;
        }
        return $slice;
    }
}

if (!function_exists('getOrderBy'))
{
    //根据tags-list规则，获取查询排序，用于标签文件 TagArclist / TagList
    function getOrderBy($orderby,$orderWay,$isrand=false){
        switch ($orderby) {
            case 'hot':
            case 'click':
                $orderby = "a.click {$orderWay}";
                break;
            case 'id': // 兼容织梦的写法
            case 'aid':
                $orderby = "a.aid {$orderWay}";
                break;
            case 'now':
            case 'new': // 兼容织梦的写法
            case 'pubdate': // 兼容织梦的写法
            case 'add_time':
                $orderby = "a.add_time {$orderWay}";
                break;
            case 'sortrank': // 兼容织梦的写法
            case 'sort_order':
                $orderby = "a.sort_order {$orderWay}";
                break;
            case 'rand':
                if (true === $isrand) {
                    $orderby = "rand()";
                } else {
                    $orderby = "a.aid {$orderWay}";
                }
                break;
            default:
            {
                if (empty($orderby)) {
                    $orderby = 'a.sort_order asc, a.aid desc';
                } elseif (trim($orderby) != 'rand()') {
                    $orderbyArr = explode(',', $orderby);
                    foreach ($orderbyArr as $key => $val) {
                        $val = trim($val);
                        if (preg_match('/^([a-z]+)\./i', $val) == 0) {
                            $val = 'a.'.$val;
                            $orderbyArr[$key] = $val;
                        }
                    }
                    $orderby = implode(',', $orderbyArr);
                }
                break;
            }
        }
        return $orderby;
    }
}

if (!function_exists('arctype_options'))
{
    //过滤和排序所有文章栏目，返回一个带有缩进级别的数组
    function arctype_options($spec_id, $arr, $id_alias, $pid_alias)
    {
        $cat_options = array();
        if (isset($cat_options[$spec_id])){
            return $cat_options[$spec_id];
        }
        if (!isset($cat_options[0]))
        {
            $level = $last_id = 0;
            $options = $id_array = $level_array = array();
            while (!empty($arr))
            {
                foreach ($arr AS $key => $value)
                {
                    $id = $value[$id_alias];
                    if ($level == 0 && $last_id == 0)
                    {
                        if ($value[$pid_alias] > 0){
                            break;
                        }
                        $options[$id]          = $value;
                        $options[$id]['level'] = $level;
                        $options[$id][$id_alias]    = $id;
                        unset($arr[$key]);
                        if ($value['has_children'] == 0){
                            continue;
                        }
                        $last_id  = $id;
                        $id_array = array($id);
                        $level_array[$last_id] = ++$level;
                        continue;
                    }
                    if ($value[$pid_alias] == $last_id)
                    {
                        $options[$id]          = $value;
                        $options[$id]['level'] = $level;
                        $options[$id][$id_alias]    = $id;
                        unset($arr[$key]);
                        if ($value['has_children'] > 0)
                        {
                            if (end($id_array) != $last_id){
                                $id_array[] = $last_id;
                            }
                            $last_id    = $id;
                            $id_array[] = $id;
                            $level_array[$last_id] = ++$level;
                        }
                    }
                    elseif ($value[$pid_alias] > $last_id){
                        break;
                    }
                }
                $count = count($id_array);
                if ($count > 1){
                    $last_id = array_pop($id_array);
                }
                elseif ($count == 1)
                {
                    if ($last_id != end($id_array)){
                        $last_id = end($id_array);
                    }else{
                        $level = 0;
                        $last_id = 0;
                        $id_array = array();
                        continue;
                    }
                }
                if ($last_id && isset($level_array[$last_id])){
                    $level = $level_array[$last_id];
                }else{
                    $level = 0;
                    break;
                }
            }
            $cat_options[0] = $options;
        }else{
            $options = $cat_options[0];
        }
        if (!$spec_id){
            return $options;
        }else{
            if (empty($options[$spec_id]))
            {
                return array();
            }
            $spec_id_level = $options[$spec_id]['level'];
            foreach ($options AS $key => $value)
            {
                if ($key != $spec_id){
                    unset($options[$key]);
                }else{
                    break;
                }
            }
            $spec_id_array = array();
            foreach ($options AS $key => $value)
            {
                if (($spec_id_level == $value['level'] && $value[$id_alias] != $spec_id) ||
                    ($spec_id_level > $value['level'])){
                    break;
                }else{
                    $spec_id_array[$key] = $value;
                }
            }
            $cat_options[$spec_id] = $spec_id_array;
            return $spec_id_array;
        }
    }
}

if (!function_exists('get_arr_column'))
{
    /**
     * 获取数组中的某一列
     * @param array $arr 数组
     * @param string $key_name  列名
     * @return array  返回那一列的数组
     */
    function get_arr_column($arr, $key_name)
    {
        if (function_exists('array_column')) {
            return array_column($arr, $key_name);
        }
        $arr2 = array();
        foreach($arr as $key => $val){
            $arr2[] = $val[$key_name];        
        }
        return $arr2;
    }
}

if (!function_exists('every_top_dirname_list')) 
{
    /**
     * 获取一级栏目的目录名称
     */
    function every_top_dirname_list() {
        $arctypeModel = new app\common\model\Arctype();
        $result = $arctypeModel->getEveryTopDirnameList();
        return $result;
    }
}

if (!function_exists('view_logic'))
{
    /**
     * 模型对应逻辑
     * @param intval $aid 文档ID
     * @param intval $channel 栏目ID
     * @param intval $result 数组
     * @param mix $allAttrInfo 附加表数据
     * @return array
     */
    function view_logic($aid, $channel, $result = array(), $allAttrInfo = array())
    {
        $allAttrInfo_bool = $allAttrInfo;
        $result['image_list'] = $result['attr_list'] = $result['file_list'] = array();
        return $result;
    }
}

// 后台权限验证
if (!function_exists('appfile_popedom')) 
{
    function appfile_popedom($string)
    {
       $pauth = \think\facade\Db::name('menu')->field('auth')->where('auth','<>','')->select()->toArray();
        foreach ($pauth as $k => $v) {
           $ordernum[] = $v['auth'];
        }
       $ordernum = array_unique($ordernum); 
       foreach ($ordernum as $key => $value) {
            $ordernum1[$value] = true;
       }
       $admin_popedom = \think\facade\Session::get('admin_info.auth_role_info.permission');
       $role_id =  \think\facade\Session::get('admin_info.role_id');
       if($role_id < 0){
           return $ordernum1;
       }else{
            if(!$string) return false;
            $p_rs = \think\facade\Db::name('menu')->where('param',$string)->find();
            if(!$p_rs) return false;
            $gid = $p_rs["id"];
            if(\think\facade\Session::get('role_id') < 0){
                return $ordernum1;
            }else{
                $rslist = \think\facade\Db::name('menu')->where('parent_id',$gid)->select()->toArray();
            }
            if(!$rslist) return false;
            $list = array();
            foreach($rslist AS $key=>$value){
                if($admin_popedom && in_array($value["id"],$admin_popedom)){
                    $list[$value["auth"]] = true;
                }else{
                    $list[$value["auth"]] = false;
                }
            }
            return $list;    
        }
    }
}

// 后台左侧菜单1
if (!function_exists('getMenuList'))
{
    function getMenuList() {
        $menuArr = \think\facade\Cache::get('getMenuList');
        if(!$menuArr){
            $menuArr = \think\facade\Db::name('menu')->where(['parent_id'=>0,'is_show'=>1,'status'=>1])->column('*', 'id');
            foreach ($menuArr as $key => $value) {
                $menuArr[$key]['child'] = getchandList($value['id']);
            }
            \think\facade\cache::set('getMenuList',$menuArr,PCFCMS_CACHE_TIME); 
        }
        return $menuArr;
    }
}

//获取模块导航2
if (!function_exists('getchandList'))
{
    function getchandList($id) {
        $getchild1list = \think\facade\Db::name('menu')->where(['parent_id'=>$id,'is_show'=>1,'status'=>1])->order('sort asc')->column('*', 'id');
        foreach ($getchild1list as $key => $value) {
            $getchild1list[$key]['child'] = noallgetlist($value['id']);
        } 
        foreach ($getchild1list as $k => $val) {
            if(empty($val['url']) && empty($val['child'])){
                unset($getchild1list[$key]);
            }
        }
        //加入内容分类列表显示在左侧栏目
        foreach ($getchild1list as $key => $value) {
            if($key == 17){
               $getchild1list[$key]['child1'] = getmenucontent();
            }
        }
        return $getchild1list;
    }
}

// 过滤不显示的左侧导航
if (!function_exists('noallgetlist'))
{
    function noallgetlist($id) {
        $getchild1list = \think\facade\Db::name('menu')->where(['parent_id'=>$id,'is_show'=>1,'status'=>1])->order('sort asc')->column('*', 'id');
        $admin_popedom = \think\facade\Session::get('admin_info.auth_role_info.permission');
        foreach ($getchild1list as $key => $value) {
            $getchild = \think\facade\Db::name('menu')->where(['parent_id'=>$value['id'],'is_show'=>1,'status'=>1,'auth'=>'list'])->order('sort asc')->column('*', 'id');
            if(\think\facade\Session::get('admin_info.role_id') > 0){
                foreach ($getchild as $k => $val) {
                    if($admin_popedom && !in_array($val["id"],$admin_popedom)){
                        unset($getchild1list[$key]);
                    }
                }                
            }
        }
        return $getchild1list;
    }
}

// 获取导航菜单3
if (!function_exists('getchandList1'))
{
    function getchandList1($id) {
        $getchild1list = \think\facade\Db::name('menu')->where(['parent_id'=>$id,'is_show'=>1])->column('*', 'id');
        foreach ($getchild1list as $key => $value) {
            $getchild1list[$key]['child'] = getchandList2($value['id']);
        }
        return $getchild1list;
    }
}

// 获取子栏目节点4
if (!function_exists('getchandList2'))
{
    function getchandList2($id) {
        $getchild2list = \think\facade\Db::name('menu')->where(['parent_id'=>$id,'is_show'=>1])->column('*', 'id');
        foreach ($getchild2list as $key => $value) {
            $getchild2list[$key]['child'] = \think\facade\Db::name('menu')->where(['parent_id'=>$value['id'],'is_show'=>1])->column('*', 'id');
        }
        return $getchild2list;
    }
}

// 获取内容管理列表
if (!function_exists('getmenucontent'))
{
    function getmenucontent() {
        // 模型列表
        $channeltype_list = \think\facade\db::name('channel_type')->column('*', 'id');
        $arctype_list = array();
        $arctype_list1 = array();
        // 目录列表
        $arctypeLogic = new app\common\logic\ArctypeLogic();
        $where=[];
        $where[] =['is_del','=',0]; // 回收站功能
        $arctype_list = $arctypeLogic->arctype_list(0, 0, false, 0, $where, false);
        foreach ($arctype_list as $key=>$val){
            $arctype_list[$key]['channeltypename'] = $channeltype_list[$val['current_channel']]['title'];
            $arctype_list[$key]['typeurl'] = get_typeurl($val);
        }
        $arctype_list = array_merge($arctype_list);
        foreach ($arctype_list as $key => $value) {
          if($value['parent_id'] > 0 || $value['current_channel'] == 6){
              unset($arctype_list[$key]);
          }else{
              $arctype_list1[$key]['name'] = $value['typename'];
              if($channeltype_list[$value['current_channel']]['ifsystem'] == 0){
                $arctype_list1[$key]['newurl'] = url('/Custom/index',['channel'=>$value['current_channel'],'typeid'=>$value['id']])->suffix(true)->domain(false)->build();
              }else{
                $arctype_list1[$key]['newurl'] = url('/'.$channeltype_list[$value['current_channel']]['ctl_name'].'/index',['typeid'=>$value['id']])->suffix(true)->domain(false)->build();
              }             
          }
        }
        return $arctype_list1;
    }
}

// 获取栏目链接
if (!function_exists('get_typeurl')) 
{
    /**
     * 获取栏目链接
     * @param array $arctype_info 栏目信息
     * @param boolean $admin 后台访问链接，还是前台链接
     * @param  URL模式  1:动态，2：静态，3：伪静态
     */
    function get_typeurl($arctype_info = array(), $admin = true)
    {
        $pcfglobal = get_global(); //全局配置
        static $domain = null;
        null === $domain && $domain = \think\facade\request::domain();
        
        // 兼容采集没有归属栏目的文档
        if (empty($arctype_info['current_channel'])) {
            $channelRow = \think\facade\Db::name('channel_type')->field('id as channel')->where('id',1)->find();
            $arctype_info = array_merge($arctype_info, $channelRow);
        }
        static $result = null;
        null === $result && $result = \think\facade\Db::name('channel_type')->column('id, ctl_name', 'id');
        $ctl_name = '';
        if ($result) {
            $ctl_name = $result[$arctype_info['current_channel']]['ctl_name'];
        }
        static $seo_pseudo = null;
        static $seo_rewrite_format = null;
        if (null === $seo_pseudo || null === $seo_rewrite_format) {
            $seoConfig = tpCache('seo');
            $seo_pseudo = !empty($seoConfig['seo_pseudo']) ? $seoConfig['seo_pseudo'] : $pcfglobal['admin_config']['seo_pseudo'];
            $seo_rewrite_format = !empty($seoConfig['seo_rewrite_format']) ? $seoConfig['seo_rewrite_format'] : $pcfglobal['admin_config']['seo_rewrite_format'];
        }
        // 静态模式和后台打开
        if ($seo_pseudo == 2 && $admin) {
            $typeurl = $domain."/index.php/lists/index.html?tid={$arctype_info['id']}&t=".getTime();
        } else {
            $typeurl = typeurl("{$ctl_name}/lists", $arctype_info, true, $domain, $seo_pseudo, $seo_rewrite_format);
        }
        return $typeurl;
    }
}

//栏目Url生成
if (!function_exists('typeurl')) {
    /**
     * 栏目Url生成
     * @param string        $url 路由地址
     * @param string|array  $param 变量
     * @param bool|string   $suffix 生成的URL后缀
     * @param bool|string   $domain 域名
     * @param string        $seo_pseudo URL模式  1:动态，2：静态，3：伪静态
     * @param string        $seo_pseudo_format URL格式
     */
    function typeurl($url = '', $param = '', $suffix = true, $domain = false, $seo_pseudo = null, $seo_pseudo_format = null)
    {
        $pcfglobal = get_global();
        $gzpcfUrl = '';
        // 是否隐藏index.php
        $seo_inlet = $pcfglobal['admin_config']['seo_inlet'];        
        $seo_pseudo = !empty($seo_pseudo) ? $seo_pseudo : tpCache('seo.seo_pseudo');
        $seo_pseudo_format = !empty($seo_pseudo_format) ? $seo_pseudo_format : tpCache('seo.seo_rewrite_format');
        // 动态
        if ($seo_pseudo == 1) {
            if (is_array($param)) {
                $vars = array('tid' => $param['id']);
                $vars = http_build_query($vars);
            } else {
                $vars = $param;
            }
            $gzpcfUrl = pcfurl('Lists/index', array(), $suffix, $domain, $seo_pseudo, $seo_pseudo_format);
            
            $urlParam = parse_url($gzpcfUrl);
            $query_str = isset($urlParam['query']) ? $urlParam['query'] : '';
            if (empty($query_str)) {
                $gzpcfUrl .= '?';
            } else {
                $gzpcfUrl .= '&';
            }
            $gzpcfUrl .= $vars;
        } 
        // 静态
        elseif ($seo_pseudo == 2) { 
            // WAP端访问是静态页面
            if (common_ismobile() =='wap') { 
                if (is_array($param)) {
                    $vars = array('tid'  => $param['id']);
                    $vars = http_build_query($vars);
                } else {
                    $vars = $param;
                }
                if (1 == $seo_inlet) {
                   $gzpcfUrl = request()->domain().'/lists/index.html?'.$vars;
                }else{
                   $gzpcfUrl = request()->domain().'/index.php/lists/index.html?'.$vars;
                }
            }
            // PC端访问是静态页面
            else{ 
                static $seo_html_listname = null;
                null === $seo_html_listname && $seo_html_listname = tpCache('seo.seo_html_listname');
                static $seo_html_arcdir = null;
                null === $seo_html_arcdir && $seo_html_arcdir = tpCache('seo.seo_html_arcdir');
                //存放顶级目录
                if($seo_html_listname == 1)
                {
                    $dirpath = explode('/',$param['dirpath']);
                    if($param['parent_id'] == 0){
                        $url = $seo_html_arcdir.'/'.$dirpath[1].'/';
                    }else{
                        $url = $seo_html_arcdir.'/'.$dirpath[1]."/lists_".$param['id'].'.html';
                    }
                }else{
                    $url = $seo_html_arcdir.$param['dirpath'].'/';
                }
                $gzpcfUrl = $url;
                if (false !== $domain) {
                    static $re_domain = null;
                    null === $re_domain && $re_domain = request()->domain();
                    if (true === $domain) {
                        $gzpcfUrl = $re_domain.$gzpcfUrl;
                    } else {
                        $gzpcfUrl = rtrim($domain, '/').$gzpcfUrl;
                    }
                }
            }
        } 
        // 伪静态
        elseif ($seo_pseudo == 3) {
            if (is_array($param)) {
                $vars = array('tid' => $param['dirname']);
            } else {
                $vars = $param;
            }
            if ($seo_pseudo_format == 1) {
                $gzpcfUrl = pcfurl('Lists/index', $vars, $suffix, $domain, $seo_pseudo, $seo_pseudo_format);
            }else if($seo_pseudo_format == 2){
                $gzpcfUrl = pcfurl($url, $vars, $suffix, $domain, $seo_pseudo, $seo_pseudo_format);
            }
        }
        return $gzpcfUrl;
    }
}

//获取文档链接
if (!function_exists('get_arcurl')) 
{
    /**
     * 获取文档链接
     * @param array $arctype_info 栏目信息
     * @param boolean $admin 后台访问链接，还是前台链接
     */
    function get_arcurl($arcview_info = array(), $admin = true)
    {
        static $domain = null;
        null === $domain && $domain = request()->domain();
        $admin_id = \think\facade\session::get('admin_id');
        $pcfglobal = get_global(); //全局配置
        // 是否隐藏index.php
        $seo_inlet = $pcfglobal['admin_config']['seo_inlet'];    
            
        // 兼容采集没有归属栏目的文档
        if (empty($arcview_info['channel'])) {
            $channelRow = \think\facade\Db::name('channel_type')->field('id as channel')->where('id',1)->find();
            $arcview_info = array_merge($arcview_info, $channelRow);
        }
        static $result = null;
        null === $result && $result = \think\facade\Db::name('channel_type')->column('id, ctl_name', 'id');
        $ctl_name = '';
        if ($result) {
            $ctl_name = $result[$arcview_info['channel']]['ctl_name'];
        }
        static $seo_pseudo = null;
        static $seo_rewrite_format = null;
        if (null === $seo_pseudo || null === $seo_rewrite_format) {
            $seoConfig = tpCache('seo');
            $seo_pseudo = !empty($seoConfig['seo_pseudo']) ? $seoConfig['seo_pseudo'] : $pcfglobal['admin_config']['seo_pseudo'];
            $seo_rewrite_format = !empty($seoConfig['seo_rewrite_format']) ? $seoConfig['seo_rewrite_format'] : $pcfglobal['admin_config']['seo_rewrite_format'];
        }
        if ($admin) {
            // 静态打开
            if ($seo_pseudo == 2) {
                if ($seo_inlet == 1) {
                   $arcurl = $domain."/view/index.html?aid={$arcview_info['aid']}";
                }else{
                   $arcurl = $domain."/index.php/view/index.html/?aid={$arcview_info['aid']}";
                }
            } else {
                $arcurl = arcurl("{$ctl_name}/view", $arcview_info, true, $domain, $seo_pseudo, $seo_rewrite_format);
                if(1==$seo_rewrite_format){
                   $arcurl = str_replace('/View', '', $arcurl);
                }
                if (stristr($arcurl, '?')) {
                    //$arcurl .= '&admin_id='.$admin_id."&t=".getTime();
                } else {
                    //$arcurl .= '?admin_id='.$admin_id."&t=".getTime();
                }
            }
        } else {
            $arcurl = arcurl("{$ctl_name}/view", $arcview_info, true, $domain, $seo_pseudo, $seo_rewrite_format);
        }
        return $arcurl;
    }
}

//文档Url生成
if (!function_exists('arcurl')) 
{
    /**
     * 文档Url生成
     * @param string        $url 路由地址
     * @param string|array  $param 变量
     * @param bool|string   $suffix 生成的URL后缀
     * @param bool|string   $domain 域名
     * @param string        $seo_pseudo URL模式  1:动态，2：静态，3：伪静态
     * @param string        $seo_pseudo_format URL格式
     */
    function arcurl($url = '', $param = '', $suffix = true, $domain = false, $seo_pseudo = '', $seo_pseudo_format = null)
    {
        $pcfglobal = get_global(); //全局配置
        $gzpcfUrl = '';   
        // 是否隐藏index.php
        $seo_inlet = $pcfglobal['admin_config']['seo_inlet'];          
        $seo_pseudo = !empty($seo_pseudo) ? $seo_pseudo : tpCache('seo.seo_pseudo');
        static $seo_rewrite_format = null;
        null === $seo_rewrite_format && $seo_rewrite_format = $pcfglobal['admin_config']['seo_rewrite_format'];//伪静态格式        
        // 动态
        if ($seo_pseudo == 1) { 
            if (is_array($param)) {
                $vars = array('aid' => $param['aid']);
                $vars = http_build_query($vars);
            } else {
                $vars = $param;
            }
            $gzpcfUrl = pcfurl('View/index', array(), $suffix, $domain, $seo_pseudo, $seo_pseudo_format);
            $urlParam = parse_url($gzpcfUrl);
            $query_str = isset($urlParam['query']) ? $urlParam['query'] : '';
            if (empty($query_str)) {
                $gzpcfUrl .= '?';
            } else {
                $gzpcfUrl .= '&';
            }
            $gzpcfUrl .= $vars;
        }
        // 静态
        elseif ($seo_pseudo == 2) { 
            // 默认手机端以动态URL访问
            if (common_ismobile() =='wap') 
            {
                if (is_array($param)) {
                    $vars = array('aid' => $param['aid'],);
                    $vars = http_build_query($vars);
                } else {
                    $vars = $param;
                }
                $gzpcfUrl = pcfurl('View/index', $vars, true, false, 1);
            }
            // PC端访问是静态页面
            else
            { 
                if (!empty($param['htmlfilename'])){
                    $aid = $param['htmlfilename'];
                }else{
                    $aid = $param['aid'];
                }
                $url = $param['dirpath']."/{$aid}.html";
                static $seo_html_pagename = null;
                null === $seo_html_pagename && $seo_html_pagename = tpCache('seo.seo_html_pagename');
                static $seo_html_arcdir = null;
                null === $seo_html_arcdir && $seo_html_arcdir = tpCache('seo.seo_html_arcdir');
                if($seo_html_pagename == 1){//存放顶级目录
                    $dirpath = explode('/',$param['dirpath']);
                    $url = $seo_html_arcdir.'/'.$dirpath[1].'/'.$aid.'.html';
                } else if ($seo_html_pagename == 3) {
                    $dirpath = explode('/',$param['dirpath']);
                    $url = $seo_html_arcdir.'/'.end($dirpath).'/'.$aid.'.html';
                }else{
                    $url = $seo_html_arcdir.$param['dirpath'].'/'.$aid.'.html';
                }
                $gzpcfUrl = $url;
                if (false !== $domain) {
                    static $re_domain = null;
                    null === $re_domain && $re_domain = request()->domain();
                    if (true === $domain) {
                        $gzpcfUrl = $re_domain.$gzpcfUrl;
                    } else {
                        $gzpcfUrl = rtrim($domain, '/').$gzpcfUrl;
                    }
                }
            }
        }
        // 伪静态 
        elseif ($seo_pseudo == 3) {
            if (1 == intval($seo_rewrite_format)) {
                $url = 'View/index';
                // URL里第一层级固定是顶级栏目的目录名称
                static $tdirnameArr = null;
                null === $tdirnameArr && $tdirnameArr = every_top_dirname_list();
                if (!empty($param['dirname']) && isset($tdirnameArr[md5($param['dirname'])]['tdirname'])) {
                    $param['dirname'] = $tdirnameArr[md5($param['dirname'])]['tdirname'];
                }
            }
            if (is_array($param)) {
                $vars = array(
                    'aid'   => $param['aid'],
                    'dirname'   => $param['dirname'],
                );
            } else {
                $vars = $param;
            }
            $gzpcfUrl = pcfurl($url, $vars, $suffix, $domain, $seo_pseudo, $seo_pseudo_format);
        }
        return $gzpcfUrl;
    }
}

//最终生成
if (!function_exists('pcfurl')) 
{
    /**
     * pcfurl生成
     * @param string        $url 路由地址
     * @param string|array  $vars 变量
     * @param bool|string   $suffix 生成的URL后缀
     * @param bool|string   $domain 域名
     * @param string        $seo_pseudo URL模式
     * @param string        $seo_pseudo_format URL格式
     * @return string       $seo_pcf_format 判断是处理列表还是内容规则
     */
    function pcfurl($url = '', $vars = '', $suffix = true, $domain = false, $seo_pseudo = null, $seo_pseudo_format = null)
    {    
        $seo_pseudo = !empty($seo_pseudo) ? $seo_pseudo : tpCache('seo.seo_pseudo');
        // 是否隐藏index.php
        $seo_inlet = tpCache('seo.seo_inlet');
        if (1 == $seo_inlet) {
            $url = url($url, $vars)->suffix('html')->root(false)->build();
        }else{
            $url = url($url, $vars)->suffix('html')->root('/index.php')->build();
        }
        if($seo_pseudo == 1){$url = strtolower($url);}
        $newurl = str_replace('/home', '', $url);//访问前台
        $newurl = str_replace('/admin', '', $newurl);//后台访问前台
        $newa = substr($newurl,0,strrpos($newurl,'php'));
        $newa = $newa."php";
        $newurl = str_replace($newa, '', $newurl);//后台访问前台
        return $newurl;
    }
}